package uade.distribuidas.server.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import uade.distribuidas.repo.exception.ExceptionUser;
import uade.distribuidas.repo.type.EstadoType;
import uade.distribuidas.server.domain.User;
import uade.distribuidas.server.hibernate.HibernateUtil;

public class UsersDAO {
	private static UsersDAO instancia = null;
	private static SessionFactory sf = null;

	public static UsersDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new UsersDAO();
		} 
		return instancia;
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getUsers() throws ExceptionUser{
		Session session = sf.openSession();
		
		List<User> lista = session.createQuery("from User where estado =:estado").setParameter("estado", EstadoType.ACTIVO).list();		
		
		session.close();
		return lista;
	}
	
	
	public User getUser(Integer id)throws ExceptionUser{
		Session session = sf.openSession();
		
		User u = (User) session.createQuery("from User where id = :id")
				.setParameter("id", id)
				.uniqueResult();			
		
		session.close();
		return u;
	}

	public User save(User u) throws ExceptionUser{
		Session session = sf.openSession();
		 Transaction transaction = session.beginTransaction();
		 transaction.begin();
		 session.saveOrUpdate(u);
		 transaction.commit();
		 session.close();
		 return u;
	}

	public User authenticate(String u, String p) throws ExceptionUser{
		Session session = sf.openSession();
		
		User user = (User) session.createQuery("from User where username = :u and password = :p and estado = :estado")
				.setParameter("u",u)
				.setParameter("p",p)
				.setParameter("estado", EstadoType.ACTIVO)
				.uniqueResult();
				
		
		session.close();
		return user;
	}
	
	
	
	

}
